<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="queryForm" :inline="true" :model="listQuery" >
        <el-form-item>
          <el-input :placeholder="$t('table.from')" v-model="listQuery.from" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
        </el-form-item>
        <el-form-item>
          <el-input :placeholder="$t('table.name')" v-model="listQuery.name" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="listQuery.createdAt"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="-"
            :start-placeholder="$t('placeholder.date_from')"
            :end-placeholder="$t('placeholder.date_to')"
            value-format="yyyy-MM-dd hh:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
          <!-- <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button> -->
          <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleMulDelete">{{ $t('table.batch_delete') }}</el-button>
          <el-button v-waves class="filter-item" type="success" icon="el-icon-download"  @click="onDownLoad">{{ $t('table.download') }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-tabs v-model="activeName" type="card" @tab-click="handleFilter">
      <el-tab-pane :label="$t('order_element.orderfrom.even')" name="first">
        <el-table
          v-loading="listLoading"
          :key="tableKey"
          :data="list"
          border
          fit
          highlight-current-row
          @selection-change="handleSelectionChange"
          style="width: 100%;">
          <el-table-column
            type="selection"
            width="35">
          </el-table-column>
          <el-table-column :label="$t('table.id')" align="center" width="65">
            <template slot-scope="scope">
              <span>{{ scope.row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.from')" min-width="150px">
            <template slot-scope="scope">
              <span>{{ scope.row.from }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.name')" min-width="150px">
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.email')" min-width="150px">
            <template slot-scope="scope">
              <span>{{ scope.row.email }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.contact_no')" min-width="150px">
            <template slot-scope="scope">
              <span>{{ scope.row.contact_no }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.company')" min-width="150px">
            <template slot-scope="scope">
              <span>{{ scope.row.company }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.message')" min-width="150px">
            <template slot-scope="scope">
              <span>{{ scope.row.message }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.created_at')" width="160px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.created_at }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.updated_at')" width="160px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.updated_at }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
              <el-button size="mini" type="danger" @click="deleteData(scope.row)">{{ $t('table.delete') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="900px">
          <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="margin-left:50px;">
          <el-form-item :label="$t('table.from')">
              <el-input v-model="temp.from" name="title1" />
            </el-form-item>
          <el-form-item :label="$t('table.name')">
              <el-input v-model="temp.name" name="name" />
            </el-form-item>
            <el-form-item :label="$t('table.email')">
              <el-input v-model="temp.email" name="email" />
            </el-form-item>
            <el-form-item :label="$t('table.contact_no')">
              <el-input v-model="temp.contact_no" name="contact_no" />
            </el-form-item>
            <el-form-item :label="$t('table.company')">
              <el-input v-model="temp.company" name="company" />
            </el-form-item>
            <el-form-item :label="$t('table.message')">
              <el-input v-model="temp.message" name="message" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
            <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>


      <el-tab-pane :label="$t('order_element.orderfrom.workshop')" name="second">
        <el-table
          v-loading="listLoading2"
          :key="tableKey2"
          :data="list2"
          border
          fit
          highlight-current-row
          @selection-change="handleSelectionChange2"
          style="width: 100%;">
          <el-table-column
            type="selection"
            width="35">
          </el-table-column>
          <el-table-column :label="$t('table.id')" align="center" width="65">
            <template slot-scope="scope">
              <span>{{ scope.row.id }}</span>
            </template>
          </el-table-column>
           <el-table-column :label="$t('table.from')" min-width="150px">
            <template slot-scope="scope">
              <span>{{ scope.row.from }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.first_name')" min-width="150px">
            <template slot-scope="scope">
              <span>{{ scope.row.first_name }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.last_name')" min-width="150px">
            <template slot-scope="scope">
              <span>{{ scope.row.last_name }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.pure_card_no')" min-width="150px">
            <template slot-scope="scope">
              <span>{{ scope.row.pure_card_no }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.number_of_participants')" min-width="150px">
            <template slot-scope="scope">
              <span>{{ scope.row.number_of_participants }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.email')" min-width="150px">
            <template slot-scope="scope">
              <span>{{ scope.row.email }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.contact_number')" min-width="150px">
            <template slot-scope="scope">
              <span>{{ scope.row.contact_number }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.day')" min-width="150px">
            <template slot-scope="scope">
              <span>{{ scope.row.days }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.product')" min-width="200px">
            <template slot-scope="scope">
              <span v-html="scope.row.group_name" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.created_at')" width="160px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.created_at }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.updated_at')" width="160px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.updated_at }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="handleUpdate2(scope.row)">{{ $t('table.edit') }}</el-button>
              <el-button size="mini" type="danger" @click="deleteData2(scope.row)">{{ $t('table.delete') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total2>0" :total="total2" :page.sync="listQuery.page2" :limit.sync="listQuery.limit2" @pagination="getList2" />

        <el-dialog :title="textMap[dialogStatus2]" :visible.sync="dialogFormVisible2" width="900px">
          <el-form ref="dataForm2" :rules="rules2" :model="temp" label-position="left" label-width="100px" style="margin-left:50px;">
            <el-form-item :label="$t('table.from')">
              <el-input v-model="temp2.from" name="title2" />
            </el-form-item>
            <el-form-item :label="$t('table.first_name')">
              <el-input v-model="temp2.first_name" name="first_name" />
            </el-form-item>
            <el-form-item :label="$t('table.last_name')">
              <el-input v-model="temp2.last_name" name="last_name" />
            </el-form-item>
            <el-form-item :label="$t('table.pure_card_no')">
              <el-input v-model="temp2.pure_card_no" name="pure_card_no" />
            </el-form-item>
            <el-form-item :label="$t('table.number_of_participants')">
              <el-input v-model="temp2.number_of_participants" name="number_of_participants" />
            </el-form-item>
            <el-form-item :label="$t('table.email')">
              <el-input v-model="temp2.email" name="email" />
            </el-form-item>
            <el-form-item :label="$t('table.contact_number')">
              <el-input v-model="temp2.contact_number" name="contact_number" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible2 = false">{{ $t('table.cancel') }}</el-button>
            <el-button type="primary" @click="dialogStatus2==='create'?createData2():updateData2()">{{ $t('table.confirm') }}</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { fetchList, fetchShow, fetchStore, fetchUpdate, fetchDelete, fetchBatchDelete } from '@/api/quotation'
import { fetchList as fetchList2, fetchShow as fetchShow2, fetchStore as fetchStore2, fetchUpdate as fetchUpdate2, fetchDelete as fetchDelete2, fetchBatchDelete as fetchBatchDelete2 } from '@/api/workshop'
import waves from '@/directive/waves' // Waves directive
import { parseTime, urlEncode, formatData } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import i18n from '@/lang/index'

export default {
  name: 'Tag',
  components: { Pagination },
  directives: { waves },
  filters: {
    availableFilter(status) {
      const availableMap = [
        'danger',
        'success'
      ]
      return availableMap[status]
    }
  },
  data() {
    return {
      //gggglobe: this.$store.state.locale.global, // store例子
      activeName: 'first',
      isAvailable: 2,
      tableKey: 0,
      tableKey2: 0,
      list: null,
      list2: null,
      content: ``,
      total: 0,
      total2: 0,
      listLoading: true,
      listLoading2: true,
      listQuery: {
        page2: 1,
        limit2: 20,
        page: 1,
        limit: 20,
        available: 2,
        from:'',
        name: '',
        createdAt: [],
        lang: i18n.locale,
      },
      quotation_ids: [],
      workshop_ids: [],
      availableOptions: [{ 'value': 2, 'name': i18n.t('table_element.available.all') }, { 'value': 1, 'name': i18n.t('table_element.available.on') }, {'value': 0, 'name': i18n.t('table_element.available.un') }],
      // areaOptions: [{ name : '中国香港', id: 1 }, { name : '中国大陆', id: 2 }],
      showReviewer: false,
      temp: {
        id: '',
        from: '',
        name: '',
        email: '',
        contact_no: '',
        company: '',
        message: '',
      },
      temp2: {
        id: '',
        from: '',
        first_name: '',
        last_name: '',
        pure_card_no: '',
        number_of_participants: '',
        email: '',
        contact_number: '',
      },
      dialogFormVisible: false,
      dialogStatus: '',
      dialogFormVisible2: false,
      dialogStatus2: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        name: [{ required: true, message: 'name is required', trigger: 'blur' }]
      },
      rules2: {
        name: [{ required: true, message: 'name is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  computed: {
  },
  methods: {
    getList() {
      this.listLoading = true
      if (this.listQuery.createdAt.length>0) {
        this.listQuery.created_at = [formatData(this.listQuery.createdAt[0]).substr(0, 10), formatData(this.listQuery.createdAt[1]).substr(0, 10)]
      } else {
        delete this.listQuery.created_at
      }
      fetchList(this.listQuery).then(response => {
        //console.log(response)
        var data = response.data
        this.list = data.data.data
        this.total = data.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getList2() {
      this.listLoading2 = true
      if (this.listQuery.createdAt.length>0) {
        this.listQuery.created_at = [formatData(this.listQuery.createdAt[0]).substr(0, 10), formatData(this.listQuery.createdAt[1]).substr(0, 10)]
      } else {
        delete this.listQuery.created_at
      }
      fetchList2(this.listQuery).then(response => {
        //console.log(response)
        var data = response.data
        this.list2 = data.data.data
        this.total2 = data.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading2 = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.listQuery.page2 = 1
      this.getList()
      this.getList2()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: 'Successful operation',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        name: '',
        email: '',
        contact_no: '',
        company: '',
        message: '',
      }
    },
    resetTemp2() {
      this.temp2 = {
        id: undefined,
        title: '',
        first_name: '',
        last_name: '',
        pure_card_no: '',
        number_of_participants: '',
        email: '',
        contact_number: '',
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreate2() {
      this.resetTemp2()
      this.dialogStatus2 = 'create'
      this.dialogFormVisible2 = true
      this.$nextTick(() => {
        this.$refs['dataForm2'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          this.temp.lang = i18n.locale
          fetchStore(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Create Success!',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    createData2() {
      this.$refs['dataForm2'].validate((valid) => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          this.temp2.lang = i18n.locale
          fetchStore2(this.temp2).then(() => {
            this.list.unshift(this.temp2)
            this.dialogFormVisible2 = false
            this.$notify({
              title: 'Success',
              message: 'Create Success!',
              type: 'success',
              duration: 2000
            })
            this.getList2()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate2(row) {
      this.temp2 = Object.assign({}, row) // copy obj
      this.temp2.timestamp = new Date(this.temp2.timestamp)
      this.dialogStatus2 = 'update'
      this.dialogFormVisible2 = true
      this.$nextTick(() => {
        this.$refs['dataForm2'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.lang = i18n.locale
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          fetchUpdate(this.temp.id, tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Success!',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    updateData2() {
      this.$refs['dataForm2'].validate((valid) => {
        if (valid) {
          this.temp2.lang = i18n.locale
          const tempData = Object.assign({}, this.temp2)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          fetchUpdate2(this.temp2.id, tempData).then(() => {
            for (const v of this.list2) {
              if (v.id === this.temp2.id) {
                const index = this.list2.indexOf(v)
                this.list2.splice(index, 1, this.temp2)
                break
              }
            }
            this.dialogFormVisible2 = false
            this.$notify({
              title: 'Success',
              message: 'Update Success!',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      // console.log(row);
      this.$notify({
        title: 'Success',
        message: 'Delete Success!',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    handleDelete2(row) {
      // console.log(row);
      this.$notify({
        title: 'Success',
        message: 'Delete Success!',
        type: 'success',
        duration: 2000
      })
      const index = this.list2.indexOf(row)
      this.list2.splice(index, 1)
    },
    deleteData(row) {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        fetchDelete(row.id).then(response => {
          var data = response.data
          if (data.code == 0) {
            this.$notify({
              title: 'Success',
              message: 'Delete Success!',
              type: 'success',
              duration: 2000
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          }
          
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    deleteData2(row) {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        fetchDelete2(row.id).then(response => {
          var data = response.data
          if (data.code == 0) {
            this.$notify({
              title: 'Success',
              message: 'Delete Success!',
              type: 'success',
              duration: 2000
            })
            const index = this.list2.indexOf(row)
            this.list2.splice(index, 1)
          }
          
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    handleMulDelete() {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        // console.log(this.activeName);
        // return ;
        if (this.activeName == 'first') {
          fetchBatchDelete({ quotation_id: this.quotation_ids }).then(response => {
            var data = response.data
            if (data.code == 0) {
              this.$notify({
                title: 'Success',
                message: 'Delete Success!',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        } else if (this.activeName == 'second') {
          fetchBatchDelete2({ workshop_id: this.workshop_ids }).then(response => {
            var data = response.data
            if (data.code == 0) {
              this.$notify({
                title: 'Success',
                message: 'Delete Success!',
                type: 'success',
                duration: 2000
              })
              this.getList2()
            }
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    handleSelectionChange(val) {
      val.forEach(element => {
        if (this.quotation_ids.indexOf(element.id) == -1) {
          this.quotation_ids.push(element.id)
        }
      })
    },
    handleSelectionChange2(val) {
      val.forEach(element => {
        if (this.workshop_ids.indexOf(element.id) == -1) {
          this.workshop_ids.push(element.id)
        }
      })
    },
    onDownLoad() { //跳转下载页
      let url = ''
      if (this.listQuery.createdAt) {
        this.listQuery.created_at = [formatData(this.listQuery.createdAt[0]).substr(0, 10), formatData(this.listQuery.createdAt[1]).substr(0, 10)]
      } else {
        delete this.listQuery.created_at
      }
      let query = urlEncode(this.listQuery)
      if (this.activeName == 'first') {
        url = process.env.BASE_API + '/admin/quotation-export?1=1' + query
      } else {
        url = process.env.BASE_API + '/admin/workshop-export?1=1' + query
      }
      window.open(url)
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
